<?php

namespace app\trait;

use app\constant\CommonConstant;
use app\exception\PaypalBusinessException;
use app\libs\PaypalSDK\action\PurchasePaypal;
use app\model\Notify;
use app\model\Orders;
use app\model\Shops;
use Shopify\Auth\FileSessionStorage;
use Shopify\Auth\Session;
use Shopify\Context;
use think\helper\Arr;

trait PaymentTrait
{
    protected ?Shops $shop = null;

    public function setUp($shop_id = 0)
    {
        $this->setShop($shop_id);//设置店铺
        $path = runtime_path('/tmp/php_sessions');
        $scopes = [
            'unauthenticated_read_product_listings',
            'unauthenticated_read_product_tags',
            'unauthenticated_read_checkouts',
            'unauthenticated_write_checkouts'
        ];
        //dd($shop_id,$this->shop->api_key,$this->shop->api_secret,$this->shop->api_host,$this->shop->version);
        Context::initialize(
            apiKey: $this->shop->api_key,
            apiSecretKey: $this->shop->api_secret,
            scopes: $scopes,
            hostName: $this->shop->api_host,
            sessionStorage: new FileSessionStorage($path),
            apiVersion: $this->shop->version,
            isEmbeddedApp: true,
            isPrivateApp: false,
        );
    }

    public function getPaySession(): Session
    {
        $session = new Session(uniqid(time()), $this->shop->api_host, true, md5(time()));
        $session->setAccessToken($this->shop->admin_token);
        return $session;
    }

    protected function setShop($shop_id = 0)
    {
        $shop_id = $shop_id ?: request()->middleware('x_shop_id');
        $this->shop = Shops::query()->find($shop_id);
    }

    public function getShop()
    {
        return $this->shop;
    }

    //执行贝宝支付
    public function executePaypalCapture(Orders $order,$token,$is_repurchase=0)
    {
        $client = new PurchasePaypal($order->payment);
        //获取详情
        $transaction_id = $token;
        $payRes = $client->fetchPurchase($transaction_id);
        $payRes = $payRes['result'];
        if (empty($payRes)) throw new PaypalBusinessException('订单异常');
        if (isset($payRes['error']) && !empty($payRes['error'])) throw new PaypalBusinessException('paypal error: ' . $payRes['error']['message']);
        if (isset($payRes['status']) && $payRes['status'] != 'COMPLETED') {
            #2.执行支付
            $paymentSource = [
                'payment_source' => [
                    'token' => [
                        'id' => $transaction_id,
                        'type' => 'BILLING_AGREEMENT'
                    ],
                ],
            ];
            $payRes = $client->completePurchase($transaction_id, $paymentSource);
            $payRes = $payRes['result'];
            Notify::saveParams($order->id,['params'=>$paymentSource,'response'=>$payRes],$is_repurchase ? Notify::TYPE_CAPTURE_PURCHASE: Notify::TYPE_CAPTURE_ORDER);
            //交易ID
            $purchase_units = $payRes['purchase_units'] ?? [];
            $sourceTradeId = $order->transaction_id;
            $tradeId = '';
            if ($purchase_units) {
                $purchaseFirst = Arr::first($purchase_units);
                $payments = $purchaseFirst['payments'];
                $capturesFirst = Arr::first($payments['captures']);
                $tradeId = $capturesFirst['id'];
            }
            $tradeArr = $sourceTradeId ? [$sourceTradeId] : [];
            if ($tradeId) $tradeArr[] = $tradeId;
            $order->transaction_id = implode(',', $tradeArr);
            //保存支付结果
            $key = $is_repurchase ? CommonConstant::SECOND_PAY_KEY : CommonConstant::FIRST_PAY_KEY;
            $placeOrderResult = $order->place_order_result;
            if(array_key_exists($key,$placeOrderResult)){
                $placeOrderResult[$key]['notify'] = $payRes;
            }else{
                $placeOrderResult['notify'] = $payRes;
            }
            $order->place_order_result = $placeOrderResult;
            $order->save();
        }
        return $payRes['status'] == 'COMPLETED';
    }


}